import {InputNumFormatterReg} from "./ConstField";
import {ifTrue} from "../redare/utils/Utils";
import moment from "moment";
import {getStorage} from "./StorageUtils";

//获取用户数据
export function getUserId() {
    return getStorage("userId");
}


//转换为树形结构数据
export function _changeData(data, parentId = 0) {
    let parentArr = [];
    data.forEach(item => {
        if (item.parentId == parentId) {
            parentArr.push(item)
        }
    });
    return _generateChildrenData(parentArr, data)
}

const _generateChildrenData = function (parentArr, data) {
    parentArr.forEach(item => {
        let children = data.filter(record => item.id === record.parentId);
        if (children.length > 0) {
            item.children = children;
        }
        if (item.children && item.children.length > 0) {
            _generateChildrenData(item.children, data)
        }
    });
    return parentArr
};

/**
 * 字符串转数字
 * @param value
 * @returns {number}
 */
export function strToNum(value) {
    try {
        if (ifTrue(value) && (value.constructor === Number || value.constructor === String)) {
            value = Number(value);
            if (isNaN(value) === true) {
                value = undefined;
            }
        }
    } catch (e) {
        console.error(e);
        value = undefined;
    }
    return value;
}

/**
 * 获取对象的指定值
 * @author WanJie.Peng
 * @date 2020-7-16 12:01:34
 * @param obj 要取字段的源对象
 * @param fieldName 字段名称
 * @param emptySymbol 数据为空时，代替的符号， 比如 -
 */
export function getValue(obj, fieldName, emptySymbol) {
    if (!emptySymbol) {
        emptySymbol = '';
    }
    if (!obj || !ifTrue(obj[fieldName])) {
        return emptySymbol;
    }
    return obj[fieldName];
}

/**
 *
 * @param obj 要取字段的源对象
 * @param fieldName 字段名称
 * @param switchObj 要进行switch的对象 格式： {obj[fieldName]: value}
 * @param emptySymbol
 * 2020-8-25 15:22:20 WanJie.Peng
 * @returns {*|string}
 */
export function getValueOfStatusObj(obj, fieldName, switchObj, emptySymbol) {
    let key = getValue(obj, fieldName, emptySymbol);
    // 如果key无效或者等于替代符返回key
    if (!ifTrue(key) || key === emptySymbol) {
        return key;
    }
    // 从源数据中获取真正的状态值
    let value = getValue(switchObj, key);
    return value ? value : '';
}

/**
 * 获取金额字符串
 * @date 2020-8-12 22:03:45
 * @author WanJie.Peng
 * @param value
 * @param pointLength 小数点补充位数
 * @returns {*}
 */
export function getMoneyStr(value, pointLength = 0) {
    if (!value) {
        return '';
    }

    value = `${value}`.replace(InputNumFormatterReg, ',');
    if (pointLength > 0) {
        let pointArray = value.split(".");
        if (pointArray.length > 1) {
            value = pointArray[1].length === 1 ? (value + "0") : value;
        } else {
            value = value + ".00";
        }
    }

    return value;
}

/**
 * 获取服务器时间
 * 2020-10-12 11:57:32
 * @author WanJie.Peng
 */
export async function getServerDate() {

    return new Promise((resolve, reject) => {

        fetch('/').then((response) => {
            let date = response.headers.get('Date');
            let current_date_str = moment(date).format('YYYY-MM-DD');
            let current_date_year = current_date_str.substring(0, 4);
            let current_date_month = current_date_str.substring(5, 7);
            let current_date_day = current_date_str.substring(8, 10);

            let result = {
                date,
                dateStr: current_date_str,
                year: current_date_year,
                month: current_date_month,
                day: current_date_day,
            }

            resolve(result);
        });
    });
}

/**
 * 将阿拉伯数字转为简体汉字（例：12 to 十二）
 * @param num
 * @returns {string}
 */
export function arabia_to_simplifiedChinese(num) {
    for (let i = num.length - 1; i >= 0; i--) {
        num = num.replace(",", "")//替换Num中的“,”
        num = num.replace(" ", "")//替换Num中的空格
    }
    if (isNaN(num)) { //验证输入的字符是否为数字
        return "";
    }
    //字符处理完毕后开始转换，采用前后两部分分别转换
    let part = String(num).split(".");
    let newChar = "";
    //小数点前进行转化
    for (let i = part[0].length - 1; i >= 0; i--) {
        //若数量超过拾亿单位，返回
        if (part[0].length > 10) {
            return "";
        }
        let tmpNewChar = ""
        let perChar = part[0].charAt(i);
        switch (perChar) {
            case "0":
                tmpNewChar = "零" + tmpNewChar;
                break;
            case "1":
                tmpNewChar = "一" + tmpNewChar;
                break;
            case "2":
                tmpNewChar = "二" + tmpNewChar;
                break;
            case "3":
                tmpNewChar = "三" + tmpNewChar;
                break;
            case "4":
                tmpNewChar = "四" + tmpNewChar;
                break;
            case "5":
                tmpNewChar = "五" + tmpNewChar;
                break;
            case "6":
                tmpNewChar = "六" + tmpNewChar;
                break;
            case "7":
                tmpNewChar = "七" + tmpNewChar;
                break;
            case "8":
                tmpNewChar = "八" + tmpNewChar;
                break;
            case "9":
                tmpNewChar = "九" + tmpNewChar;
                break;
        }
        switch (part[0].length - i - 1) {
            case 0:
                tmpNewChar = tmpNewChar;
                break;
            case 1:
                if (perChar != 0) tmpNewChar = tmpNewChar + "十";
                break;
            case 2:
                if (perChar != 0) tmpNewChar = tmpNewChar + "百";
                break;
            case 3:
                if (perChar != 0) tmpNewChar = tmpNewChar + "千";
                break;
            case 4:
                tmpNewChar = tmpNewChar + "万";
                break;
            case 5:
                if (perChar != 0) tmpNewChar = tmpNewChar + "十";
                break;
            case 6:
                if (perChar != 0) tmpNewChar = tmpNewChar + "百";
                break;
            case 7:
                if (perChar != 0) tmpNewChar = tmpNewChar + "千";
                break;
            case 8:
                tmpNewChar = tmpNewChar + "亿";
                break;
            case 9:
                tmpNewChar = tmpNewChar + "十";
                break;
        }
        newChar = tmpNewChar + newChar;
    }
    //替换所有无用汉字，直到没有此类无用的数字为止
    while (newChar.search("零零") !== -1 ||
        newChar.search("零亿") !== -1 ||
        newChar.search("亿万") !== -1 ||
        newChar.search("零万") !== -1
        ) {
        newChar = newChar.replace("零亿", "亿");
        newChar = newChar.replace("亿万", "亿");
        newChar = newChar.replace("零万", "万");
        newChar = newChar.replace("零零", "零");
    }
    //替换以“一十”开头的，为“十”
    if (newChar.indexOf("一十") === 0) {
        newChar = newChar.substr(1);
    }
    //替换以“零”结尾的，为“”
    if (newChar.lastIndexOf("零") === newChar.length - 1) {
        newChar = newChar.substr(0, newChar.length - 1);
    }
    return newChar;
}

/**
 * 将简体汉字数字转为阿拉伯数字（例：十二 to 12）
 * @param chnStr
 * @returns {boolean|number|*}
 */
export function simplifiedChinese_to_arabia(chnStr) {
    let chnNumChar = {
        零: 0, 一: 1, 二: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9
    };
    let chnNameValue = {
        十: {value: 10, secUnit: false},
        百: {value: 100, secUnit: false},
        千: {value: 1000, secUnit: false},
        万: {value: 10000, secUnit: true},
        亿: {value: 100000000, secUnit: true}
    };
    let expNumChar = {十: 10, 十一: 11, 十二: 12, 十三: 13, 十四: 14, 十五: 15, 十六: 16, 十七: 17, 十八: 18, 十九: 19};
    if (expNumChar[chnStr]) {
        return expNumChar[chnStr];
    }
    let rtn = 0;
    let section = 0;
    let number = 0;
    let secUnit = false;
    let str = chnStr.split('');
    for (let i = 0; i < str.length; i++) {
        let num = chnNumChar[str[i]];
        if (typeof num !== 'undefined') {
            number = num;
            if (i === str.length - 1) {
                section += number;
            }
        } else {
            let cunit = chnNameValue[str[i]];
            if (typeof cunit == 'undefined') {
                return false;
            }
            let unit = chnNameValue[str[i]].value;
            secUnit = chnNameValue[str[i]].secUnit;
            if (secUnit) {
                section = (section + number) * unit;
                rtn += section;
                section = 0;
            } else {
                section += (number * unit);
            }
            number = 0;
        }
    }
    return rtn + section;
}


/**
 * module 样式解析
 * 2020-11-24 10:03:05 pwj
 * @param Style
 * @param str
 * @returns {string}
 */
export function moduleStyleAnalysis(Style, ...str) {
    if (!str) {
        return '';
    }
    let attr = [];
    if (str.constructor === Array) {
        if (str.length === 1) {
            attr = str[0].split(' ');
        } else {
            attr = str;
        }
    }
    let newStr = '';
    attr.map((item) => {
        newStr += Style[item] + ' ';
    });
    return newStr;
}


